package epoch.game.core.net;

import java.nio.ByteBuffer;
import java.util.List;

import epoch.game.core.server.ISession;
import epoch.game.core.stat.StatisticsMSG;

public class MsgSender {
	public static void send(ISession session, int msgId, byte[] data) {
		int size = data.length + 2;
		int len  = size + 4;
		ByteBuffer buffer = ByteBuffer.allocate(len);
		buffer.putInt(size);
		buffer.putShort((short)msgId);
		buffer.put(data);
		
		byte[] bytes = buffer.array();
		session.writeToSendBuffer(bytes, false);
		
		StatisticsMSG.send(msgId, len);
	}
	
	public static void send(ISession session, int msgId, byte[] data, long sender, List<Long> receivers) {
		int size = data.length + 2 + 8 + 4 + receivers.size() * 8;
		int len  = size + 4;
		ByteBuffer buffer = ByteBuffer.allocate(len);
		buffer.putInt(size);
		buffer.putShort((short)msgId);
		buffer.putLong(sender);
		buffer.putInt(receivers.size());
		for (Long roleId : receivers) {
			buffer.putLong(roleId.longValue());
		}
		buffer.put(data);
		
		byte[] bytes = buffer.array();
		session.writeToSendBuffer(bytes, false);
		
		StatisticsMSG.send(msgId, len);
	}
	
	public static void broadcast(List<ISession> sessions, int msgId, byte[] data) {
		for(ISession session : sessions){
			send(session, msgId, data);
		}
	}
}